/*
 * // +-------------------------------------------------------------------------------------------------
 * // |                 有你就好 [ 有节骨乃坚，无心品自端 ]     <http://encoding.wang>
 * // +-------------------------------------------------------------------------------------------------
 * // |                             独在异乡为异客         每逢佳节倍思亲
 * // +-------------------------------------------------------------------------------------------------
 * // |                 联系:   <707069100@qq.com>      <http://weibo.com/513778937>
 * // +-------------------------------------------------------------------------------------------------
 */

// -----------------------------------------------------------------------------------------------------
// +----------------------------------------------------------------------------------------------------
// |                   ErYang出品 属于小极品          共同学习    共同进步
// +----------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------


package wang.encoding.mroot.admin.common.quartz


import org.apache.commons.lang3.StringUtils
import org.quartz.JobExecutionContext
import org.quartz.JobExecutionException
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.quartz.QuartzJobBean
import wang.encoding.mroot.admin.common.config.AdminTaskExecutePoolConfiguration
import wang.encoding.mroot.common.util.SpringContextUtil
import wang.encoding.mroot.model.entity.system.ScheduleJob
import wang.encoding.mroot.model.entity.system.ScheduleJobLog
import wang.encoding.mroot.model.enums.ScheduleJobStatusEnum
import wang.encoding.mroot.service.system.ScheduleJobLogService

import java.math.BigInteger
import java.net.InetAddress
import java.net.UnknownHostException
import java.time.Duration
import java.time.Instant


/**
 * 定时任务 Bean
 *
 * @author ErYang
 */
class QuartzScheduleJob : QuartzJobBean() {

    companion object {


        private val logger: Logger = LoggerFactory.getLogger(QuartzScheduleJob::class.java)

        // -------------------------------------------------------------------------------------------------

        /**
         * 获取本机IP
         *
         * @return ip
         */
        private val localIp: String?
            get() {
                var ip: String? = null
                try {
                    val ineptAddress: InetAddress = InetAddress.getLocalHost()
                    ip = ineptAddress.hostAddress
                } catch (e: UnknownHostException) {
                    e.printStackTrace()
                }

                return ip
            }
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 线程池
     */
    @Suppress("SpringKotlinAutowiredMembers")
    @Autowired
    //private val taskExecutor: TaskExecutor? = null
    private val taskExecutor: AdminTaskExecutePoolConfiguration? = null


    @Throws(JobExecutionException::class)
    override fun executeInternal(jobExecutionContext: JobExecutionContext) {

        // 得到定时任务
        val scheduleJob: ScheduleJob = jobExecutionContext.mergedJobDataMap["scheduleJob"] as ScheduleJob

        val scheduleJobLogService: ScheduleJobLogService = SpringContextUtil.getSpringContextUtil()!!.getBean("scheduleJobLogServiceImpl")

        // 数据库保存执行记录
        val scheduleJobLog = ScheduleJobLog()
        scheduleJobLog.scheduleJobId = scheduleJob.id
        scheduleJobLog.title = scheduleJob.title
        scheduleJobLog.beanName = scheduleJob.beanName
        scheduleJobLog.methodName = scheduleJob.methodName
        scheduleJobLog.params = scheduleJob.params
        scheduleJobLog.cronExpression = scheduleJob.cronExpression

        // 任务开始时间
        val start: Instant = Instant.now()

        // 执行任务
        val quartzScheduleJobRunnable: QuartzScheduleJobRunnable

        try {
            quartzScheduleJobRunnable = QuartzScheduleJobRunnable(scheduleJob.beanName!!,
                    scheduleJob.methodName!!, scheduleJob.params)
            taskExecutor!!.adminTaskExecutePool().execute(quartzScheduleJobRunnable)
            // 任务执行总时长
            val end: Instant = Instant.now()
            val timeElapsed: Duration = Duration.between(start, end)
            val times: BigInteger = BigInteger.valueOf(timeElapsed.toMillis())
            scheduleJobLog.times = times
            scheduleJobLog.executionResult = ScheduleJobStatusEnum.SUCCEED.value
            // 定时任务状态 任务状态 1：成功 2：失败 详情请见：ScheduleJobStatusEnum
            scheduleJobLog.status = ScheduleJobStatusEnum.SUCCEED.key

        } catch (e: Exception) {
            if (logger.isErrorEnabled) {
                logger.error(">>>>>>>>执行定时任务失败[{}]：{}<<<<<<<<", scheduleJob, e.message)
            }
            // 任务执行总时长
            val end: Instant = Instant.now()
            val timeElapsed: Duration = Duration.between(start, end)
            val times: BigInteger = BigInteger.valueOf(timeElapsed.toMillis())
            scheduleJobLog.times = times
            scheduleJobLog.executionResult = ScheduleJobStatusEnum.FAILED.value
            // 定时任务状态 任务状态 1：成功 2：失败 详情请见：ScheduleJobStatusEnum
            scheduleJobLog.status = ScheduleJobStatusEnum.FAILED.key
            scheduleJobLog.errorMessage = StringUtils.substring(e.toString(), 0, 2000)
        } finally {
            scheduleJobLog.gmtCreateIp = localIp
            // 保存数据到数据库
            scheduleJobLogService.initSaveScheduleJobLog(scheduleJobLog)
            scheduleJobLogService.saveBackId(scheduleJobLog)
        }
    }

    // -------------------------------------------------------------------------------------------------

}

// -----------------------------------------------------------------------------------------------------

// End QuartzScheduleJob class

/* End of file QuartzScheduleJob.kt */
/* Location: ./src/main/kotlin/wang/encoding/mroot/admin/common/quartz/QuartzScheduleJob.kt */

// -----------------------------------------------------------------------------------------------------
// +----------------------------------------------------------------------------------------------------
// |                           ErYang出品 属于小极品  O(∩_∩)O~~   共同学习    共同进步
// +----------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------
